package com.dom.domweb.dao.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dom.common.constants.ConstantError;
import com.dom.common.exception.ServiceException;
import com.dom.domweb.dao.entity.TRolePrivRel;
import com.dom.domweb.dao.mapper.TRolePrivRelMapper;
import com.dom.domweb.dao.service.ITRolePrivRelService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dom.domweb.model.MenuNode;
import com.dom.domweb.model.RolePrivsModel;
import com.dom.domweb.modular.shiro.model.ShiroUser;
import com.xiaoleilu.hutool.collection.CollectionUtil;
import com.xiaoleilu.hutool.util.ArrayUtil;
import com.xiaoleilu.hutool.util.ObjectUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * B_角色权限关系表 服务实现类
 * </p>
 *
 * @author xllei
 * @since 2018-11-17
 */
@Service
public class TRolePrivRelServiceImpl extends ServiceImpl<TRolePrivRelMapper, TRolePrivRel> implements ITRolePrivRelService {
    @Override
    public boolean resetPrivileges(ShiroUser user, RolePrivsModel rolePrivsModel) {
        if(CollectionUtil.isEmpty(rolePrivsModel.getData())){
            throw new ServiceException(ConstantError.NOT_PRIVS_ERROR);
        }
        if (ObjectUtils.isEmpty(rolePrivsModel.getRoleId())) {
            throw new ServiceException(ConstantError.NO_ROLE_ERROR);
        }

        Wrapper<TRolePrivRel> wrapper = new EntityWrapper<>();
        wrapper.eq("mem_code", user.getMemCode())
                .eq("role_code", rolePrivsModel.getRoleId());
        boolean result = this.delete(wrapper);

        List<TRolePrivRel> rolePrivRels = new ArrayList<>();
        rolePrivsModel.getData().forEach(roleMenuInfo->{
            TRolePrivRel rolePrivRel = new TRolePrivRel();
            rolePrivRel.setMemCode(user.getMemCode());
            rolePrivRel.setRoleCode(rolePrivsModel.getRoleId());
            rolePrivRel.setMenuId(roleMenuInfo.getMenuId());

            rolePrivRels.add(rolePrivRel);
        });

        boolean res = this.insertBatch(rolePrivRels);

        return res;
    }
}
